package diploma.kisel.modelas.repository;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import diploma.kisel.hibernate.util.HibernateUtil;
import diploma.kisel.modelas.domain.Computer;
import diploma.kisel.modelas.domain.ComputerType;
import diploma.kisel.modelas.repository.api.ComputerRepository;

public class ComputerRepositoryImpl implements ComputerRepository{
	
	private EntityManager em = HibernateUtil.getEm();

	@Override
	public List<Computer> findAll() {
		List<Computer> computers= em.createNamedQuery(
				"Computer.findAll", Computer.class).getResultList();		
		return computers;		
	}

	@Override
	public List<Computer> findByPrice(int minPrice, int maxPrice) {
		TypedQuery<Computer> query = em.createNamedQuery(
				"Computer.findByPrice", Computer.class);
		query.setParameter("minPrice", minPrice);
		query.setParameter("maxPrice", maxPrice);
		return query.getResultList();
	}
	
	

	@Override
	public Computer save(Computer computer) {
		em.getTransaction().begin();
		em.persist(computer);
		em.getTransaction().commit();
		return computer;
	}

	@Override
	public Computer update(Computer computer) {
		em.getTransaction().begin();
		em.merge(computer);
		em.getTransaction().commit();
		return computer;
	}

	@Override
	public void remove(Computer computer) {
		em.getTransaction().begin();
		Computer mergedComputer = em.merge(computer);
		em.remove(mergedComputer);			
		em.getTransaction().commit();		
	}

	@Override
	public Computer findById(int id) {
		TypedQuery<Computer> query = em.createNamedQuery("Computer.findById", Computer.class);
		query.setParameter("id", id);
		return query.getSingleResult();
	}

	@Override
	public List<Computer> findByType(ComputerType type) {
		TypedQuery<Computer> query = em.createNamedQuery("Computer.findByType", Computer.class);
		query.setParameter("type", type);
		return query.getResultList();
	}

	@Override
	public List<Computer> findByPriceAndType(int min, int max, ComputerType type) {
		TypedQuery<Computer> query = em.createNamedQuery(
				"Computer.findByPriceAndType", Computer.class);
		query.setParameter("minPrice", min);
		query.setParameter("maxPrice", max);
		query.setParameter("type", type);
		return query.getResultList();
	}

}
